import json
import requests



MONITOR = {
    'score': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=eaa423a5-607d-44b8-a20f-f5971b9e5712',
    'dm': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=97db91a8-4f7f-4c88-8ef7-438178931f36',
    'jintiao': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4455dcbf-6411-4f50-926b-6b4ccb1942a7',
    'pingfenka_upload': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=5ac3dbf1-456a-4705-aeec-bc9f20828b3b&type=file',
    'pingfenka_send': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5ac3dbf1-456a-4705-aeec-bc9f20828b3b',
    'renren_label': 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4f13a555-fdbe-4066-8143-7a815fff3a12',
    'num':'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4f13a555-fdbe-4066-8143-7a815fff3a12',
    'null_warning':'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=4f13a555-fdbe-4066-8143-7a815fff3a12'
}


# 将报警信息发送到企业微信
def send_wechat_warning(content, window, level, alarm=None):
    import traceback
    try:
        headers = {
            'Content-Type': 'application/json'
        }
        title = '{}:{}'.format(level, window)

        text = {}
        text['content'] = "{}\n{}".format(title, content)
        if alarm:
            if isinstance(alarm, str):
                text["mentioned_mobile_list"] = [alarm]
            elif isinstance(alarm, list):
                text["mentioned_mobile_list"] = alarm

        request_body = {'msgtype': 'text', 'text': text}
        payLoad = json.dumps(request_body)

        response = requests.request("POST", MONITOR.get(window), headers=headers, data=payLoad, timeout=1)
        content = response.text
        return content
    except Exception as ee:
        traceback.print_exc()
        return ''

# 将报警信息发送到企业微信
def send_wechat_file(file):
    upload_url = MONITOR.get("pingfenka_upload")
    send_url = MONITOR.get("pingfenka_send")
    # 传入文件
    data = {'file': open(file, 'rb')}
    # 请求id_url(将文件上传微信临时平台),返回media_id
    response = requests.post(url=upload_url, files=data, timeout=5)
    json_res = response.json()
    media_id = json_res['media_id']
    data = {"msgtype": "file",
            "file": {"media_id": media_id}
            }
    result = requests.post(url=send_url, json=data, timeout=5)
    return result
